//
//  XS_KCZhiboVC.swift
//  XueDao
//
//  Created by 韩云智 on 2021/1/1.
//

import UIKit
import RxCocoa
import RxSwift
import RxDataSources
import SnapKit

class XS_KCqueryByLiveIdCurriculumsM: XS_BaseModel {
    var vipPrice = "" // vip价格
    var curriculumNum = "" // 课程数
    var curriculumImgurl = "" // 课程图片地址
    var purchaseNum = "" // 购买人数
    var discountPrice = "" // 优惠价格
    var price = "" // 课程价格
    var introduce = "" // 课程简介
    var curriculumName = "" // 课程名称
    var curriculumId = 0 // 课程id
    var liveId = 0 // 直播id
    var id = 0 // id（中间表id，后台用）
    var curriculumForm = "online"
}
class XS_KCqueryByLiveIdM: XS_BaseModel {
    var userType = "" // 当前登录用户是不是vip，判断显示价格，空值代表没有登录
    var Curriculums: [XS_KCqueryByLiveIdCurriculumsM] = []
}

class XS_KCZhiboVC: XS_BaseVC {
    weak var player: XS_KCVideo?
    deinit {
        player?.player?.destroy()
    }
    lazy var id = ""
    var model: XS_KCqueryLiveByIdM?
    lazy var dataPS = PublishSubject<XS_KCqueryLiveByIdM>()
    lazy var ss = getScroll()
    
    func onAction(_ type: XS_KCBaseVC.ActionType) {
        guard let model = model else { return }
        switch type {
        case .分享:
            guard let url = URL(string: "/course?id=\(model.id)".spliceH5Api()) else { return }
            let activityVc = UIActivityViewController(activityItems: [url], applicationActivities: nil)
            XS_NVC.shared.present(activityVc, animated: true)
        case .想学:
            if model.isCollection == "yesCollection" {
                model.isCollection = "noCollection"
                _ = XS_NetWork.requestJson("/collection/collectionCancel", parameters: ["relation":model.id,"type":"live"])
                    .subscribe()
            } else {
                model.isCollection = "yesCollection"
                _ = XS_NetWork.requestJson("/collection/collectionButton", parameters: ["relation":model.id,"type":"live"])
                    .subscribe()
            }
            dataPS.onNext(model)
        default: break
        }
    }
    
    override func upConfig() {
        shouldNavBarHidden = true
        isStatusBarBlack = false
    }
    lazy var isPlay = false
    override func upView() {
        Observable<Int>.interval(.seconds(60), scheduler: MainScheduler.asyncInstance)
            .subscribe(onNext: { [weak self] _ in
                guard XS_Singleton.shared.infoModel != nil, let `self` = self, self.isPlay else { return }
                _ = XS_NetWork.requestJson("/plan/uploadUserLearnTime", parameters: ["time": "1"])
                    .subscribe()
            }).disposed(by: disposeBag)
        
        view.addSubview(ss)
        let top = UIView()
        top.alpha = 0
        top.backgroundColor = #colorLiteral(red: 0.1647058824, green: 0.7411764706, blue: 0.6117647059, alpha: 1)
        view.addSubview(top)
        loadCustomBar()
        
        top.snp.makeConstraints({
            $0.left.right.top.equalToSuperview()
            $0.bottom.equalTo(customBar.snp.bottom)
        })
        ss.snp.makeConstraints({
            $0.left.right.top.bottom.equalToSuperview()
        })
        
        ss.rx.contentOffset
            .subscribe(onNext: { offset in
                top.alpha = offset.y / (.scale*240 - 44 - .barHeight)
            }).disposed(by: disposeBag)
        
        let share = QMUIButton()
        share.setBackgroundImage(UIImage(named: "icon_分享备份"), for: .normal)
        view.addSubview(share)
        share.snp.makeConstraints({
            $0.width.height.equalTo(24)
            $0.centerY.equalTo(customBar.snp.centerY)
            $0.right.equalTo(-16)
        })
        share.rx.tap.asDriver()
            .drive(onNext: { [weak self] in
                self?.onAction(.分享)
            }).disposed(by: disposeBag)
        
        
        let xiangxue = QMUIButton()
        xiangxue.isHidden = true
        xiangxue.setBackgroundImage(UIImage(named: "icon_24px_收藏_1"), for: .normal)
        xiangxue.setBackgroundImage(UIImage(named: "icon_64_收藏_绿_1"), for: .selected)
        view.addSubview(xiangxue)
        xiangxue.snp.makeConstraints({
            $0.width.height.equalTo(24)
            $0.centerY.equalTo(customBar.snp.centerY)
            $0.right.equalTo(-56)
        })
        xiangxue.rx.tap.asDriver()
            .drive(onNext: { [weak self] in
                self?.onAction(.想学)
            }).disposed(by: disposeBag)
        
        let video = XS_KCVideo()
        player = video
        ss.addSubview(video)
        video.snp.makeConstraints({
            $0.top.left.width.equalToSuperview()
            $0.height.equalTo(.scale*240)
        })
        
        let biaoqian = XS_KCBiaoqian(["介绍", "购买"]) { [weak self] index in
            guard let `self` = self else { return nil }
            switch index {
            case 0: return self.getJieshao()
            case 1: return self.getTuijian()
            default: return nil
            }
        }
        ss.addSubview(biaoqian)
        biaoqian.snp.makeConstraints({
            $0.top.equalTo(video.snp.bottom)
            $0.left.width.equalToSuperview()
            $0.bottom.lessThanOrEqualToSuperview()
        })
        
        dataPS.subscribe(onNext: { model in
            video.imgPS.onNext(model.liveCover)
            xiangxue.isHidden = false
            xiangxue.isSelected = model.isCollection == "yesCollection"
        }).disposed(by: disposeBag)
        XS_NetWork.requestJson("/live/queryLiveById", parameters: ["id":id])
            .mapModel(type: XS_KCqueryLiveByIdM.self)
            .subscribe(onNext: { [weak self] model, resp in
                guard let `self` = self, resp.success, let model = model else { return }
                self.model = model
                self.dataPS.onNext(model)
                video.livePS.onNext(model.liveUrl)
            }).disposed(by: disposeBag)
    }
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        guard model != nil else { return }
        XS_NetWork.requestJson("/live/queryLiveById", parameters: ["id":id])
            .mapModel(type: XS_KCqueryLiveByIdM.self)
            .subscribe(onNext: { [weak self] model, resp in
                guard let `self` = self, resp.success, let model = model else { return }
                self.model = model
                self.dataPS.onNext(model)
            }).disposed(by: disposeBag)
    }
    
    private func getJieshao() -> UIView {
        let view = UIView()
        
        let topView = UIView()
        topView.backgroundColor = #colorLiteral(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0)
        view.addSubview(topView)
        var constraint: Constraint!
        topView.snp.makeConstraints({
            $0.left.top.right.equalToSuperview()
            constraint = $0.height.equalTo(0).constraint
            $0.bottom.lessThanOrEqualToSuperview()
        })
        let timeView = UIView()
        timeView.isHidden = true
        timeView.layer.cornerRadius = .scale*4
        timeView.layer.borderWidth = 1
        timeView.layer.borderColor = #colorLiteral(red: 0.9411764706, green: 0.9490196078, blue: 0.968627451, alpha: 1)
        topView.addSubview(timeView)
        timeView.snp.makeConstraints({
            $0.width.equalTo(.scale*343)
            $0.height.equalTo(.scale*200)
            $0.top.equalTo(.scale*16)
            $0.centerX.equalToSuperview()
        })
        let btn = QMUIButton()
        btn.layer.cornerRadius = .scale*20
        btn.layer.backgroundColor = #colorLiteral(red: 0.1647058824, green: 0.7411764706, blue: 0.6117647059, alpha: 1)
        btn.setTitle("开播提醒", for: .normal)
        btn.setTitleColor(#colorLiteral(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0), for: .normal)
        btn.titleLabel?.font = .xsFont(name: .medium, .scale*16)
        timeView.addSubview(btn)
        btn.snp.makeConstraints({
            $0.width.equalTo(.scale*215)
            $0.height.equalTo(.scale*40)
            $0.centerX.equalToSuperview()
            $0.top.equalTo(.scale*144)
        })
        
        let fm = DateFormatter()
        fm.dateFormat = "yyyy-MM-dd HH:mm:ss"
        dataPS.take(1)
            .subscribe(onNext: { [weak self] model in
                guard let `self` = self else { return }
                if let startTime = model.startTime.components(separatedBy: ".").first?.replacingOccurrences(of: "T", with: " "),
                   let date = fm.date(from: startTime),
                   date.timeIntervalSince(Date()) > 0 {
                    let tv = self.getTimeView(date)
                    timeView.addSubview(tv)
                    tv.snp.makeConstraints({
                        $0.top.equalTo(.scale*46)
                        $0.centerX.equalToSuperview()
                    })
                    
                    btn.rx.tap.asDriver()
                        .drive(onNext: { [weak self] in
                            guard let `self` = self else { return }
                            
                            XS_NetWork.requestJson("/live/insertReservationLive", parameters: [
                                "id":self.id
                            ]).subscribe(onNext: { [weak self] resp in
                                if resp.success {
                                    let calendar = EventCalendar.shared()
                                    calendar?.createEventCalendarTitle("开播提醒", location: model.title, start: date, end: date, allDay: false, alarmArray: ["0"])
                                    model.isReservation = "yesReservation"
                                    btn.isHidden = true
                                }
                                self?.view.xsShowMsg(resp.msg)
                            }).disposed(by: self.disposeBag)
                        }).disposed(by: self.disposeBag)
                }
                var last = topView
                if model.teachers.count > 0 {
                    let teacher = XS_KCTeachers()
                    view.addSubview(teacher)
                    teacher.snp.makeConstraints({
                        $0.left.width.equalToSuperview()
                        $0.top.equalTo(last.snp.bottom)
                        $0.bottom.lessThanOrEqualToSuperview()
                    })
                    teacher.modelPS.onNext(model.teachers)
                    last = teacher
                }
                if model.description.count > 0 {
                    let zhengshu = XS_KCZhengshu()
                    view.addSubview(zhengshu)
                    zhengshu.snp.makeConstraints({
                        $0.left.width.equalToSuperview()
                        $0.top.equalTo(last.snp.bottom)
                        $0.bottom.lessThanOrEqualToSuperview()
                    })
                    zhengshu.modelPS.onNext(("直播介绍", model.description))
                    last = zhengshu
                }
        }).disposed(by: disposeBag)
        
        
        let tLab = UILabel()
        tLab.textAlignment = .center
        timeView.addSubview(tLab)
        tLab.snp.makeConstraints({
            $0.top.equalTo(.scale*16)
            $0.centerX.equalToSuperview()
        })
        let pLab = UILabel.xsLabel(size: .scale*16, fontName: .regular, color: #colorLiteral(red: 0.5333333333, green: 0.5568627451, blue: 0.5764705882, alpha: 1), alignment: .center, text: "4321 人已预约")
        timeView.addSubview(pLab)
        pLab.snp.makeConstraints({
            $0.top.equalTo(.scale*98)
            $0.centerX.equalToSuperview()
        })
        
        dataPS.subscribe(onNext: { [weak self] model in
            if let startTime = model.startTime.components(separatedBy: ".").first?.replacingOccurrences(of: "T", with: " "),
               let date = fm.date(from: startTime),
               date.timeIntervalSince(Date()) > 0 {
                let text = NSMutableAttributedString()
                do {
                    let attr = NSMutableAttributedString(string: "距离 ")
                    attr.yy_color = #colorLiteral(red: 0.4470588235, green: 0.4666666667, blue: 0.4862745098, alpha: 1)
                    text.append(attr)
                }
                do {
                    let fm1 = DateFormatter()
                    fm1.dateFormat = "MM-dd HH:mm"
                    let attr = NSMutableAttributedString(string: fm1.string(from: date))
                    attr.yy_color = #colorLiteral(red: 0.9294117647, green: 0.3960784314, blue: 0.2470588235, alpha: 1)
                    text.append(attr)
                }
                do {
                    let attr = NSMutableAttributedString(string: " 直播开始还有")
                    attr.yy_color = #colorLiteral(red: 0.4470588235, green: 0.4666666667, blue: 0.4862745098, alpha: 1)
                    text.append(attr)
                }
                text.yy_font = .xsFont(name: .regular, .scale*16)
                tLab.attributedText = text
                pLab.text = "\(model.reservationCount) 人已预约"
                
                view.bringSubviewToFront(topView)
                constraint.update(offset: .scale*216)
                timeView.isHidden = false
                
                btn.isHidden = model.isReservation == "yesReservation"
            } else {
                constraint.update(offset: 0)
                timeView.isHidden = true
                self?.isPlay = true
            }
        }).disposed(by: disposeBag)
        return view
    }
    
    private func getTuijian() -> UIView {
        let view = UIView()
        
        let head = UIView(frame: CGRect(x: 0, y: 0, width: .screenWidth, height: .scale*56))
        let label = UILabel.xsLabel(size: .scale*16, fontName: .medium, color: #colorLiteral(red: 0.2196078431, green: 0.2352941176, blue: 0.2470588235, alpha: 1), text: "推荐课程")
        head.addSubview(label)
        label.snp.makeConstraints({
            $0.left.equalTo(.scale*16)
            $0.centerY.equalToSuperview()
        })
        
        let table = UITableView(frame: .zero, style: .grouped)
        table.showsVerticalScrollIndicator = false
        table.contentInsetAdjustmentBehavior = .never
        table.bounces = false
        table.backgroundColor = .clear
        table.separatorStyle = .none
        table.rowHeight = .scale*108
        table.sectionHeaderHeight = 0
        table.sectionFooterHeight = 0
        table.tableHeaderView = head
        table.tableFooterView = UIView(frame: CGRect(x: 0, y: 0, width: .screenWidth, height: 0.01))
        table.register(XS_KCZhiboCell.self, forCellReuseIdentifier: "cell")
        view.addSubview(table)
        var constraint: Constraint!
        table.snp.makeConstraints({
            $0.top.left.right.equalToSuperview()
            constraint = $0.height.equalTo(.scale*57).constraint
            $0.bottom.lessThanOrEqualToSuperview()
        })
        table.rx.observe(CGSize.self, "contentSize")
            .subscribe(onNext: { size in
                guard let size = size, size != .zero else { return }
                constraint.update(offset: size.height)
            }).disposed(by: self.disposeBag)
        
        let dataSource = RxTableViewSectionedReloadDataSource<SectionModel<String, XS_KCqueryByLiveIdCurriculumsM>>(configureCell: { ds, tv, ip, it in
            let text = ds.sectionModels[ip.section].model
            let cell = tv.dequeueReusableCell(withIdentifier: "cell", for: ip) as! XS_KCZhiboCell
            cell.modelPS.onNext((text == "vip", it))
            return cell
        })
        table.rx.modelSelected(XS_KCqueryByLiveIdCurriculumsM.self)
            .asDriver()
            .drive(onNext: { [weak self] item in
                guard let `self` = self else { return }
                self.player?.player?.pause()
                let vc = item.curriculumForm == "" ? XS_KeChengVC() : XS_KCXianxiaVC()
                vc.id = "\(item.id)"
                XS_NVC.shared.pushViewController(vc, animated: true)
            }).disposed(by: disposeBag)
        XS_NetWork.requestJson("/liveCurriculum/queryByLiveId", parameters: ["liveId": self.id])
            .mapModel(type: XS_KCqueryByLiveIdM.self)
            .compactMap { $0.1.success ? $0.0 : nil }
            .flatMapLatest { Driver.just([SectionModel<String, XS_KCqueryByLiveIdCurriculumsM>(model: $0.userType, items: $0.Curriculums)]) }
            .asDriver(onErrorJustReturn: [])
            .drive(table.rx.items(dataSource: dataSource))
            .disposed(by: self.disposeBag)
        return view
    }
    private func getScroll() -> UIScrollView {
        let scroll = UIScrollView()
        scroll.backgroundColor = #colorLiteral(red: 0.968627451, green: 0.968627451, blue: 0.968627451, alpha: 1)
        scroll.bounces = false
        scroll.contentInsetAdjustmentBehavior = .never
        scroll.showsVerticalScrollIndicator = false
        return scroll
    }
    
    func getTimeView(_ date: Date) -> UIView {
        let view = UIView()
        let arr = ["天","时","分","秒"]
        var last: UIView?
        var labs: [UILabel] = []
        for text in arr {
            let item = getTimeItem(text)
            item.text = "--"
            view.addSubview(item)
            item.snp.makeConstraints({
                $0.top.equalToSuperview()
                $0.right.lessThanOrEqualTo(-.scale*18)
                if let last = last {
                    $0.left.equalTo(last.snp.right).offset(.scale*43)
                } else {
                    $0.left.equalToSuperview()
                }
            })
            last = item
            labs.append(item)
        }
        reloadTime(date, labs: labs)
        return view
    }
    func reloadTime(_ date: Date, labs: [UILabel]) {
        let s = date.timeIntervalSince(Date())
        guard s > 0 else {
            labs[0].text = "00"
            labs[1].text = "00"
            labs[2].text = "00"
            labs[3].text = "00"
            if let model = model {
                dataPS.onNext(model)
            }
            return
        }
        labs[0].text = String(format: "%.2ld", Int(s)/3600/24)
        labs[1].text = String(format: "%.2ld", Int(s)/3600%24)
        labs[2].text = String(format: "%.2ld", Int(s)/60%60)
        labs[3].text = String(format: "%.2ld", Int(s)%60)
        Driver.just(()).delay(.seconds(1))
            .drive(onNext: { [weak self] in
                self?.reloadTime(date, labs: labs)
            }).disposed(by: disposeBag)
    }
    func getTimeItem(_ text: String) -> UILabel {
        let label = UILabel.xsLabel(size: .scale*32, fontName: .semibold, color: #colorLiteral(red: 0.2196078431, green: 0.2352941176, blue: 0.2470588235, alpha: 1))
        let dLab = UILabel.xsLabel(size: .scale*14, fontName: .regular, color: #colorLiteral(red: 0.2196078431, green: 0.2352941176, blue: 0.2470588235, alpha: 1), text: text)
        label.addSubview(dLab)
        dLab.snp.makeConstraints({
            $0.top.equalTo(.scale*18)
            $0.left.equalTo(label.snp.right).offset(.scale*3)
        })
        return label
    }
}

class XS_KCZhiboCell: XS_BaseTCell {
    lazy var modelPS = PublishSubject<(Bool,XS_KCqueryByLiveIdCurriculumsM)>()
    
    override func upView() {
        selectionStyle = .none // 去掉点击样式
        backgroundColor = .clear
        
        let bgView = UIView()
        bgView.backgroundColor = #colorLiteral(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0)
        contentView.addSubview(bgView)
        bgView.snp.makeConstraints({
            $0.edges.equalTo(UIEdgeInsets(top: 0, left: .scale*16, bottom: .scale*12, right: .scale*16))
        })
        
        let view = getXianxia()
        bgView.addSubview(view)
        view.snp.makeConstraints({
            $0.edges.equalTo(UIEdgeInsets(top: .scale*12, left: .scale*12, bottom: .scale*12, right: .scale*12))
        })
    }
    
    func getXianxia() -> UIView {
        let view = UIView()
        
        let imgV = UIImageView()
        imgV.layer.masksToBounds = true
        imgV.layer.cornerRadius = .scale * 4
        imgV.frame = CGRect(x: 0, y: 0, width: .scale*100, height: .scale*72)
        view.addSubview(imgV)
        imgV.layer.cornerRadius = .scale*4
        imgV.clipsToBounds = true
        
        let layerView = UIView()
        layerView.frame = CGRect(x: 0, y: 0, width: .scale*45, height: .scale*18)
        layerView.corner(byRoundingCorners: .bottomRight, radii: .scale*4)
        layerView.alpha = 1
        // fillCode
        let bglayer1 = CAGradientLayer()
        bglayer1.colors = [UIColor(red: 1, green: 0.91, blue: 0.73, alpha: 1).cgColor, UIColor(red: 0.98, green: 0.84, blue: 0.59, alpha: 1).cgColor]
        bglayer1.locations = [0, 1]
        bglayer1.frame = layerView.bounds
        layerView.layer.addSublayer(bglayer1)
        bglayer1.startPoint = CGPoint(x: 1.00, y: 0.50)
        bglayer1.endPoint = CGPoint(x: -0.00, y: 0.50)
        imgV.addSubview(layerView)
        
        let label = UILabel.xsLabel(size: .scale*10, fontName: .medium, color: #colorLiteral(red: 0.5803921569, green: 0.3490196078, blue: 0, alpha: 1), text: "VIP免费")
        layerView.addSubview(label)
        label.snp.makeConstraints({
            $0.center.equalToSuperview()
        })
        
        
        let label1 = UILabel.xsLabel(size: .scale*14, fontName: .medium, color: #colorLiteral(red: 0.2829915285, green: 0.3015331626, blue: 0.3147756159, alpha: 1), text: "可视化程序设计及应用")
        view.addSubview(label1)
        label1.snp.makeConstraints {
            $0.top.equalToSuperview()
            $0.left.equalTo(imgV.snp.right).offset(.scale*12)
            $0.right.lessThanOrEqualToSuperview().offset(-.scale*8)
        }
        let label2 = UILabel.xsLabel(size: .scale*12, fontName: .regular, color: #colorLiteral(red: 0.6666666667, green: 0.6941176471, blue: 0.7176470588, alpha: 1), text: "1242人加入学习")
        view.addSubview(label2)
        label2.snp.makeConstraints {
            $0.top.equalTo(label1.snp.bottom).offset(.scale*6)
            $0.left.equalTo(imgV.snp.right).offset(.scale*12)
            $0.right.lessThanOrEqualToSuperview().offset(-.scale*8)
        }
        let label3 = UILabel.xsLabel(size: .scale*12, fontName: .semibold, color: #colorLiteral(red: 0.9294117647, green: 0.3960784314, blue: 0.2470588235, alpha: 1), text: "共9节 | 免费")
        view.addSubview(label3)
        label3.snp.makeConstraints {
            $0.bottom.equalTo(imgV.snp.bottom)
            $0.left.equalTo(imgV.snp.right).offset(.scale*12)
            $0.width.lessThanOrEqualTo(.scale*150)
        }
        
        modelPS.subscribe(onNext: { isVip, item in
            if item.vipPrice == "0" || item.vipPrice == "" {
                layerView.isHidden = false
            } else {
                layerView.isHidden = true
            }
            imgV.sd_setImage(with: URL(string: item.curriculumImgurl))
            label1.text = item.curriculumName
            label2.text = "\(item.purchaseNum)人加入学习"
            var text = "共\(item.curriculumNum)节 | "
            if isVip {
                text += item.vipPrice == "0" ? "免费" : "￥\(item.vipPrice)"
            } else if item.discountPrice.count > 0 {
                text += item.discountPrice == "0" ? "免费" : "￥\(item.discountPrice)"
            } else {
                text += item.price == "0" ? "免费" : "￥\(item.price)"
            }
            label3.text = text
        }).disposed(by: disposeBag)
        
        return view
    }
}
